<template>
  <div class="dashboard-editor-container">
    <!--    <github-corner class="github-corner" />-->

    <panel-group ref="panelGroup" @handleSetLineChartData="handleSetLineChartData" />
    <el-row style="padding:16px 16px 0;margin-bottom:32px;">
      <el-select v-model="valueAlice" placeholder="请选择" @change="selectServer('Alice')">
        <el-option
          v-for="item in aliceServerList"
          :key="item.host"
          :label="item.host"
          :value="item.host"
        >
          <span style="float: left"><svg-icon icon-class="server" />{{ item.host }}</span>
          <span style="float: right; color: #061f41; font-size: 13px"><i class="el-icon-sort" />{{ item.currentDataRate.toFixed(2) }}</span>
        </el-option>
      </el-select>
    </el-row>
    <el-row style="background:#fff;padding:16px 16px 0;margin-bottom:32px;">
      <line-chart :chart-data="aliceLinechartData" />
    </el-row>
    <el-row align="middle" type="flex" justify="center">
      <el-button :type="startMonitoringAlice?'danger':'primary'" round @click="startMonitoring(valueAlice, 'Alice')">{{ startMonitoringAlice?'停止测速':'开始测速' }}</el-button>
    </el-row>
    <!--     服务器下行数据-->
    <el-row style="padding:16px 16px 0;margin-bottom:32px;">
      <el-select v-model="valueBob" placeholder="请选择" @change="selectServer('Bob')">
        <el-option
          v-for="item in bobServerList"
          :key="item.host"
          :label="item.host"
          :value="item.host"
        >
          <span style="float: left"><svg-icon icon-class="server" /> {{ item.host }}</span>
          <span style="float: right; color: #061f41; font-size: 13px"><i class="el-icon-sort" />{{ item.currentDataRate.toFixed(2) }}</span>
        </el-option>
      </el-select>
    </el-row>
    <el-row style="background:#fff;padding:16px 16px 0;margin-bottom:32px;">
      <line-chart :chart-data="bobLinechartData" />
    </el-row>
    <el-row align="middle" type="flex" justify="center">
      <el-button :type="startMonitoringBob?'danger':'primary'" round @click="startMonitoring(valueBob, 'Bob')">{{ startMonitoringBob?'停止测速':'开始测速' }}</el-button>
    </el-row>

    <!--    <el-row :gutter="32">-->
    <!--      <el-col :xs="24" :sm="24" :lg="8">-->
    <!--        <div class="chart-wrapper">-->
    <!--          <raddar-chart />-->
    <!--        </div>-->
    <!--      </el-col>-->
    <!--      <el-col :xs="24" :sm="24" :lg="8">-->
    <!--        <div class="chart-wrapper">-->
    <!--          <pie-chart />-->
    <!--        </div>-->
    <!--      </el-col>-->
    <!--      <el-col :xs="24" :sm="24" :lg="8">-->
    <!--        <div class="chart-wrapper">-->
    <!--          <bar-chart />-->
    <!--        </div>-->
    <!--      </el-col>-->
    <!--    </el-row>-->

    <!--    <el-row :gutter="8">-->
    <!--      <el-col :xs="{span: 24}" :sm="{span: 24}" :md="{span: 24}" :lg="{span: 12}" :xl="{span: 12}" style="padding-right:8px;margin-bottom:30px;">-->
    <!--        <transaction-table />-->
    <!--      </el-col>-->
    <!--      <el-col :xs="{span: 24}" :sm="{span: 12}" :md="{span: 12}" :lg="{span: 6}" :xl="{span: 6}" style="margin-bottom:30px;">-->
    <!--        <todo-list />-->
    <!--      </el-col>-->
    <!--      <el-col :xs="{span: 24}" :sm="{span: 12}" :md="{span: 12}" :lg="{span: 6}" :xl="{span: 6}" style="margin-bottom:30px;">-->
    <!--        <box-card />-->
    <!--      </el-col>-->
    <!--    </el-row>-->
  </div>
</template>

<script>
import dataServer from '@/api/server-result-api'
// import GithubCorner from '@/components/GithubCorner'
import PanelGroup from './components/PanelGroup'
import LineChart from './components/LineChart'
// import RaddarChart from './components/RaddarChart'
// import PieChart from './components/PieChart'
// import BarChart from './components/BarChart'
// import TransactionTable from './components/TransactionTable'
// import TodoList from './components/TodoList'
// import BoxCard from './components/BoxCard'

const lineChartData = {
  aliceOnlineServer: {
    averageDataRate: [],
    currentDataRate: [],
    bler: [],
    currentTime: []
  },
  bobOnlineServer: {
    averageDataRate: [],
    currentDataRate: [],
    bler: [],
    currentTime: []
  },
  purchases: {
    expectedData: [80, 100, 121, 104, 105, 90, 100],
    actualData: [120, 90, 100, 138, 142, 130, 130]
  },
  shoppings: {
    expectedData: [130, 140, 141, 142, 145, 150, 160],
    actualData: [120, 82, 91, 154, 162, 140, 130]
  }
}

export default {
  name: 'DashboardAdmin',
  components: {
    // GithubCorner,
    PanelGroup,
    LineChart
    // RaddarChart,
    // PieChart,
    // BarChart,
    // TransactionTable,
    // TodoList,
    // BoxCard
  },
  data() {
    return {
      aliceLinechartData: lineChartData.aliceOnlineServer,
      bobLinechartData: lineChartData.bobOnlineServer,
      aliceServerList: [],
      bobServerList: [],
      // alice类型服务器对象，用于存储所有该类型下的服务器数据的累加
      aliceServerTotal: {
        'ue_id': 'Alice',
        'onlineServer': 0,
        'offlineServer': 0,
        'host': '所有下行服务器',
        'averageDataRate': 0,
        'currentDataRate': 0,
        'bler': 0
      },
      // bob类型服务器对象，用于存储所有该类型下的服务器数据的累加
      bobServerTotal: {
        'ue_id': 'Bob',
        'onlineServer': 0,
        'offlineServer': 0,
        'host': '所有上行服务器',
        'averageDataRate': 0,
        'currentDataRate': 0,
        'bler': 0
      },
      panelGroupInfo: {
        'onlineServer': 0,
        'offlineServer': 0,
        'averageDataRateOfAlice': 0,
        'currentDataRateOfAlice': 0,
        'blerOfAlice': 0,
        'averageDataRateOfBob': 0,
        'currentDataRateOfBob': 0,
        'blerOfBob': 0
      },
      // alice标签服务器的折线图数据（累加）
      totalAliceAverageDataRate: [],
      totalAliceCurrentDataRate: [],
      totalAliceBler: [],
      // bob标签服务器的折线图数据 （累加）
      totalBobAverageDataRate: [],
      totalBobCurrentDataRate: [],
      totalBobBler: [],
      currentDateTimeAlice: [],
      currentDateTimeBob: [],
      startMonitoringAlice: false,
      startMonitoringBob: false,
      aliceQueryTimer: null,
      bobQueryTimer: null,
      valueAlice: '所有下行服务器',
      valueBob: '所有上行服务器'
    }
  },
  mounted() {
    this.queryResults('Alice')
    this.queryResults('Bob')
  },
  methods: {
    // 开始测速
    startMonitoring(monitorType, ueId) {
      // console.log(monitorType, ueId)
      if (ueId === 'Alice') {
        if (!this.startMonitoringAlice) {
          const that = this
          this.aliceQueryTimer = monitorType === '所有下行服务器' ? setInterval(function() {
            that.updateCharData(ueId)
          }, 1500) : setInterval(function() {
            that.updateChartDataByOneServer(ueId)
          }, 1500)
          this.startMonitoringAlice = true
        } else {
          this.startMonitoringAlice = false
          clearInterval(this.aliceQueryTimer)
        }
      } else if (ueId === 'Bob') {
        if (!this.startMonitoringBob) {
          const that = this
          this.bobQueryTimer = monitorType === '所有上行服务器' ? setInterval(function() {
            that.updateCharData(ueId)
          }, 1500) : setInterval(function() {
            that.updateChartDataByOneServer(ueId)
          }, 1500)
          this.startMonitoringBob = true
        } else {
          this.startMonitoringBob = false
          clearInterval(this.bobQueryTimer)
        }
      }
    },
    handleSetLineChartData(type) {
      // this.aliceLinechartData = lineChartData[type]
      // this.bobLinechartData = lineChartData[type]
    },
    // 从接口拉取数据并更新到图表中
    updateCharData(ueId) {
      this.queryResults(ueId)
      if (ueId === 'Alice') {
        this.generateChartData(7, this.aliceServerTotal, 'Alice')
      } else if (ueId === 'Bob') {
        this.generateChartData(7, this.bobServerTotal, 'Bob')
      }
      this.resetSumUp(ueId)
      this.setChartData(ueId)
      this.updatePanelGroup(this.panelGroupInfo)
    },
    // 用某个服务器的数据更新图表
    updateChartDataByOneServer(ueId) {
      this.queryResults(ueId)
      if (ueId === 'Alice') {
        this.getSpecifiedServerData(this.valueAlice, 'Alice', 7)
      } else if (ueId === 'Bob') {
        this.getSpecifiedServerData(this.valueBob, 'Bob', 7)
      }
      this.resetSumUp(ueId)
      this.setChartData(ueId)
    },
    // 将接口获取到的数据设置到panel group当中
    updatePanelGroup(panelGroupInfo) {
      this.$refs.panelGroup.updatePanelData(panelGroupInfo)
    },
    // 从后台拉取运行数据
    queryResults(ueId) {
      dataServer.getServerResults()
        .then(response => {
          const serverData = response.data
          // console.log(serverData)
          // 按照ue_id进行累加
          if (ueId === 'Alice') {
            this.sumByUeidForAlice(serverData)
          } else if (ueId === 'Bob') {
            this.sumByUeidForBob(serverData)
          }
          // this.getSpecifiedServerData('114', serverData)
        })
    },
    // // 获取下拉列表选中的服务器的实时数据
    // queryResultsForOneServer() {
    //   dataServer.getServerResults()
    //     .then(response => {
    //       const serverData = response.data
    //       this.sumByUeid(serverData)
    //     })
    // },
    // 更新图表数据
    setChartData(ueId) {
      if (ueId === 'Alice') {
        // 更新Alice
        this.aliceLinechartData.averageDataRate = this.totalAliceAverageDataRate
        this.aliceLinechartData.currentDataRate = this.totalAliceCurrentDataRate
        this.aliceLinechartData.bler = this.totalAliceBler
        this.aliceLinechartData.currentTime = this.currentDateTimeAlice
      } else if (ueId === 'Bob') {
        // 更新Bob
        this.bobLinechartData.averageDataRate = this.totalBobAverageDataRate
        this.bobLinechartData.currentDataRate = this.totalBobCurrentDataRate
        this.bobLinechartData.bler = this.totalBobBler
        this.bobLinechartData.currentTime = this.currentDateTimeBob
      }
    },
    // 按照ue_id分类累加
    sumByUeidForAlice(data) {
      const alice_server_data = []
      for (let i = 0; i < data.length; i++) {
        if (data[i].ue_id === 'Alice') {
          this.aliceServerTotal.averageDataRate += data[i].averageDataRate
          this.panelGroupInfo.averageDataRateOfAlice = this.aliceServerTotal.averageDataRate
          this.aliceServerTotal.currentDataRate += data[i].currentDataRate
          this.panelGroupInfo.currentDataRateOfAlice = this.aliceServerTotal.currentDataRate
          this.aliceServerTotal.bler += data[i].bler
          alice_server_data.push(data[i])
        }
      }
      // 误码率求平均
      this.aliceServerTotal.bler /= data.length
      this.panelGroupInfo.blerOfAlice = this.aliceServerTotal.bler
      // 设置在线/离线服务器数
      this.aliceServerTotal.onlineServer = alice_server_data.length
      this.panelGroupInfo.onlineServer = this.aliceServerTotal.onlineServer
      this.aliceServerTotal.offlineServer = 0
      this.panelGroupInfo.offlineServer = 0
      // 汇总alice 和 bob 服务器数据
      alice_server_data.push(this.aliceServerTotal)
      this.aliceServerList = alice_server_data
      // console.log(this.aliceServerTotal)
    },
    // 按照ue_id分类累加
    sumByUeidForBob(data) {
      const bob_server_data = []
      for (let i = 0; i < data.length; i++) {
        if (data[i].ue_id === 'Bob') {
          this.bobServerTotal.averageDataRate += data[i].averageDataRate
          this.panelGroupInfo.averageDataRateOfBob = this.bobServerTotal.averageDataRate
          this.bobServerTotal.currentDataRate += data[i].currentDataRate
          this.panelGroupInfo.currentDataRateOfBob = this.bobServerTotal.currentDataRate
          this.bobServerTotal.bler += data[i].bler
          bob_server_data.push(data[i])
        }
      }
      // 误码率求平均
      this.bobServerTotal.bler /= data.length
      this.panelGroupInfo.blerOfBob = this.bobServerTotal.bler
      // 设置在线/离线服务器数
      this.bobServerTotal.onlineServer = bob_server_data.length
      this.panelGroupInfo.onlineServer = this.bobServerTotal.onlineServer
      this.bobServerTotal.offlineServer = 0
      this.panelGroupInfo.offlineServer = 0
      // 汇总alice 和 bob 服务器数据
      bob_server_data.push(this.bobServerTotal)
      this.bobServerList = bob_server_data
      // console.log(this.bobServerTotal)
    },
    // 重置累加和
    resetSumUp(ueId) {
      if (ueId === 'Alice') {
        this.aliceServerTotal = {
          'ue_id': 'Alice',
          'host': '所有下行服务器',
          'averageDataRate': 0,
          'currentDataRate': 0,
          'bler': 0
        }
      } else if (ueId === 'Bob') {
        this.bobServerTotal = {
          'ue_id': 'Bob',
          'host': '所有上行服务器',
          'averageDataRate': 0,
          'currentDataRate': 0,
          'bler': 0
        }
      }
    },
    // 将获取到的累加数据按平均速率、当前速率、物块率分别设置到对应的列表中，用于折线图的展示
    generateChartData(interval, sumUpData, hostTag) {
      if (hostTag === 'Alice') {
        if (this.totalAliceAverageDataRate.length > interval) {
          this.totalAliceCurrentDataRate.shift()
          this.totalAliceAverageDataRate.shift()
          this.totalAliceBler.shift()
          this.currentDateTimeAlice.shift()
        }
        this.totalAliceAverageDataRate.push(sumUpData.averageDataRate)
        this.totalAliceCurrentDataRate.push(sumUpData.currentDataRate)
        this.totalAliceBler.push(sumUpData.bler)
        const date = new Date()
        this.currentDateTimeAlice.push(date.getHours() + ':' + date.getMinutes() + ':' + date.getSeconds())
      } else if (hostTag === 'Bob') {
        if (this.totalBobAverageDataRate.length > interval) {
          this.totalBobCurrentDataRate.shift()
          this.totalBobAverageDataRate.shift()
          this.totalBobBler.shift()
          this.currentDateTimeBob.shift()
        }
        this.totalBobAverageDataRate.push(sumUpData.averageDataRate)
        this.totalBobCurrentDataRate.push(sumUpData.currentDataRate)
        this.totalBobBler.push(sumUpData.bler)
        const date = new Date()
        this.currentDateTimeBob.push(date.getHours() + ':' + date.getMinutes() + ':' + date.getSeconds())
      }
    },
    // 获取某一特定服务器的数值
    getSpecifiedServerData(host, ueId, interval) {
      // const hostData = serverData.filter(item => item.host === host && item.ue_id === ueId)[0]
      const hostData = this.aliceServerList.filter(item => item.host === host)[0]
      if (ueId === 'Alice') {
        if (this.totalAliceAverageDataRate.length > interval) {
          this.totalAliceCurrentDataRate.shift()
          this.totalAliceAverageDataRate.shift()
          this.totalAliceBler.shift()
          this.currentDateTimeAlice.shift()
        }
        this.totalAliceAverageDataRate.push(hostData.averageDataRate)
        this.totalAliceCurrentDataRate.push(hostData.currentDataRate)
        this.totalAliceBler.push(hostData.bler)
        const date = new Date()
        this.currentDateTimeAlice.push(date.getHours() + ':' + date.getMinutes() + ':' + date.getSeconds())
      } else if (ueId === 'Bob') {
        if (this.totalBobAverageDataRate.length > interval) {
          this.totalBobCurrentDataRate.shift()
          this.totalBobAverageDataRate.shift()
          this.totalBobBler.shift()
          this.currentDateTimeBob.shift()
        }
        this.totalBobAverageDataRate.push(hostData.averageDataRate)
        this.totalBobCurrentDataRate.push(hostData.currentDataRate)
        this.totalBobBler.push(hostData.bler)
        const date = new Date()
        this.currentDateTimeBob.push(date.getHours() + ':' + date.getMinutes() + ':' + date.getSeconds())
      }
    },
    // 清空表格数据
    resetChartData(ueId) {
      if (ueId === 'Alice') {
        this.totalAliceAverageDataRate = []
        this.totalAliceCurrentDataRate = []
        this.totalAliceBler = []
        this.currentDateTimeAlice = []
        this.startMonitoringAlice = false
        clearInterval(this.aliceQueryTimer)
      } else if (ueId === 'Bob') {
        this.totalBobAverageDataRate = []
        this.totalBobCurrentDataRate = []
        this.totalBobBler = []
        this.currentDateTimeBob = []
        this.startMonitoringBob = false
        clearInterval(this.bobQueryTimer)
      }
    },
    // 选中查看某个服务器数据
    selectServer(ueId) {
      this.resetChartData(ueId)
      if (ueId === 'Alice') {
        this.startMonitoring(this.valueAlice, ueId)
      } else if (ueId === 'Bob') {
        this.startMonitoring(this.valueBob, ueId)
      }
    }
  }
}
</script>

<style lang="scss" scoped>
.dashboard-editor-container {
  padding: 32px;
  background-color: rgb(240, 242, 245);
  position: relative;

  .github-corner {
    position: absolute;
    top: 0px;
    border: 0;
    right: 0;
  }

  .chart-wrapper {
    background: #fff;
    padding: 16px 16px 0;
    margin-bottom: 32px;
  }
}

@media (max-width:1024px) {
  .chart-wrapper {
    padding: 8px;
  }
}
</style>
